package com.dupf.product.rpc.service.impl;

import com.dupf.common.util.CommonThreadPool;
import com.dupf.common.util.Tools;
import com.dupf.product.common.constant.ProductConstant;
import com.dupf.product.common.constant.ProductCountryConstant;
import com.dupf.product.dao.mapper.ProductInfoMapper;
import com.dupf.product.dao.model.ProductDetail;
import com.dupf.product.dao.model.ProductInfo;
import com.dupf.product.dao.model.ProductVariant;
import com.dupf.product.dao.model.ProductVariantExample;
import com.dupf.product.dao.smodel.ProductExportParamDTO;
import com.dupf.product.dao.smodel.ProductExportResultDTO;
import com.dupf.product.rpc.api.ProductSalePriceSettingService;
import com.dupf.product.rpc.api.ProductVariantService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * ProductExportService实现
 * Created by dupf on 2018/3/14.
 */
@Service
public class ProductExportServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductExportServiceImpl.class);
    private static final String DELIMITER = "##";
    private static final String regex1 = "<br>\\s?\\r\\n";
    private static final String regex2 = "<Br>\\s?\\r\\n";
    private static final String regex3 = "<bR>\\s?\\r\\n";
    private static final String regex4 = "<BR>\\s?\\r\\n";
    private static final String regex11 = "<br>\\s?\\n";
    private static final String regex12 = "<Br>\\s?\\n";
    private static final String regex13 = "<bR>\\s?\\n";
    private static final String regex14 = "<BR>\\s?\\n";

    @Autowired
    ProductInfoMapper productInfoMapper;
    @Autowired
    ProductSalePriceSettingService salePriceSettingService;
    @Autowired
    ProductVariantService productVariantService;

    public String exportProduct(List<ProductInfo> infos, List<ProductDetail> details, ProductExportParamDTO paramDTO) {
        XSSFWorkbook wb = null;
        FileOutputStream os = null;
        String newFileName = ProductConstant.AMAZON_TEMPLATE_BASE_PATH + System.currentTimeMillis() + Tools.getZeroNineRand(5);
        try {
            os = new FileOutputStream(new File(newFileName));


//            ClassLoader classLoader = getClass().getClassLoader();
//            File templateFile = new File(classLoader.getResource("template.xlsx").getFile());

            File templateFile = new File(ProductConstant.AMAZON_TEMPLATE_BASE_PATH + "template.xlsx");

            if (!templateFile.exists()) {
                LOGGER.info("template File not existed" + templateFile.getAbsolutePath());
                return null;
            }

            wb = new XSSFWorkbook(new FileInputStream(templateFile));

            XSSFSheet sheet = wb.getSheetAt(0);
            Row row3 = sheet.getRow(0);

            List<String> fields = new ArrayList<>();
            for (Cell cell : row3) {
                //设置单元格类型
                cell.setCellType(CellType.STRING);
                if (!StringUtils.isEmpty(cell.getStringCellValue())) {
                    fields.add(cell.getStringCellValue());
                }
            }

            int rowIndex = 1;

            int index = 0;
            for (ProductInfo info : infos) {
                ProductDetail detail = details.get(index++);
                if (!detail.getProductId().equals(info.getId())) {
                    index--;
                    continue;
                }

                Row rowNew = sheet.createRow(rowIndex);

                boolean hasVariant = StringUtils.isNotEmpty(detail.getVariantCompose()) && JSONArray.fromObject(detail.getVariantCompose()).size() > 0;

                setCellValue(fields, rowNew, paramDTO, info, detail, null, hasVariant, true);
                rowIndex++;

                if (hasVariant) {
                    JSONArray variantCompose = JSONArray.fromObject(detail.getVariantCompose());
                    for (Object o : variantCompose) {
                        JSONObject item = JSONObject.fromObject(o);
                        Row rowNewItem = sheet.createRow(rowIndex);
//                        {"variant":["color:red","size:30"],"picture":"XXX,XXX","price": 10000,"weight": 10000,"stock":100}

                        setCellValue(fields, rowNewItem, paramDTO, info, detail, item, true, false);
                        rowIndex++;
                    }
                }

            }

            wb.write(os);
            wb.close();
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFileName;
    }

    private void setCellValue(List<String> fields, Row rowNew, ProductExportParamDTO paramDTO,
                              ProductInfo info, ProductDetail detail, JSONObject variantData, boolean hasVariant, boolean isParent) {
        DecimalFormat df = new DecimalFormat("######0.00");

        String brandName = paramDTO.getBrandName();
        String manufacturer = paramDTO.getManufacturer();
        String country = paramDTO.getCountry();
        String feed = paramDTO.getFeed();
        String nodes1 = paramDTO.getNodes1();
        String nodes2 = paramDTO.getNodes2();

//        String language = getLanguage(country);
        String language = paramDTO.getLanguage();

        // 预期
        // {"variant":["color:red","size:30"],"picture":"XXX,XXX","price": 10000,"weight": 10000,"stock":100}
        // 实际
        // [{"name":"白色-S","pic":"https://cbu01.alicdn.png","stock":100},{"name":"白色-M","pic":"https://cbu01.alicdn.png","stock":100},{"name":"白色-L","pic":"https://cbu01.alicdn.png","stock":100},{"name":"白色-XL","pic":"https://cbu01.alicdn.png","stock":100}]

        String picture = null;
        Float price = null;
        Float weight = null;
        Integer stock = null;

        String colorName = "";
        String sizeName = "";

        // 主体 为了设置主体的 variation_theme
        // [{"variant":"color","args":""},{"variant":"size","args":""}]
        if (hasVariant) {
            String variant = detail.getVariant();
            if (StringUtils.isNotEmpty(variant)) {
                JSONArray variantArr = JSONArray.fromObject(variant);
                if (variantArr != null && !CollectionUtils.isEmpty(variantArr)) {
                    for (Object o : variantArr) {
                        JSONObject data = JSONObject.fromObject(o);
                        if (data.optString("variant", "").equals("color")) {
                            colorName = "color";
                        }
                        if (data.optString("variant", "").equals("size")) {
                            sizeName = "size";
                        }
                    }
                }
            }
        }

        // 变体
        if (hasVariant && !isParent && variantData != null) {

            weight = Optional.ofNullable(variantData.optDouble("weight", Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f)).orElse(0.5d).floatValue();
            picture = variantData.optString("pic");
            Double costPrice = variantData.optDouble("price", Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f);
            if (costPrice != null) {
                price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, costPrice.floatValue(), weight);
            } else {
                price = 0f;
            }
            stock = variantData.optInt("stock", 100);

            String variantName = variantData.getString("name");
            if (StringUtils.isNotEmpty(variantName)) {
                String[] variantNames = variantName.split(DELIMITER);
                Integer length = variantNames.length;
                if (length > 1) {
                    colorName = variantNames[0];
                    sizeName = variantNames[1];
                } else if (length > 0) {
                    if (colorName.equals("color")) {
                        colorName = variantNames[0];
                    } else if (sizeName.equals("size")) {
                        sizeName = variantNames[0];
                    }
                }
            }
            // 主体
        } else {
            picture = detail.getPicture();
            weight = Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f;
            price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, (Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f), weight);

            stock = detail.getStock();
        }

        // 获取币种 todo
        String saleCurrency = getSaleCurrencyByCountry(country);


        // 特殊字段
        String briefDesc = getItemBriefDesc(language, detail);
        String[] briefDescs = (briefDesc == null ? "" : briefDesc).split("\\n");

        String genericKeyword = paramDTO.getKeyWord();
//                getItemKeyword(language, detail);
        String[] genericKeywords = (genericKeyword == null ? "" : genericKeyword).split("\\n");

        String[] ppictures = (picture == null ? "" : picture).split(",");
        String[] pictures = new String[ppictures.length];
        // 处理图片为1024
//        ?imageMogr2/thumbnail/1024x
        if (ppictures != null && ppictures.length > 0) {
            for (int i = 0; i < ppictures.length; i++) {
                String pic = ppictures[i];
                if (pic.contains("pic.dupf.xin")) {
                    pic = pic + "?imageMogr2/thumbnail/1001x";
                }
                pictures[i] = pic;
            }
        }

        Cell cell = null;
        int fieldIndex = 0;
        for (String field : fields) {
            cell = rowNew.createCell(fieldIndex);// 序号
            cell.setCellType(CellType.STRING);// 文本类型

            String fieldTrim = field.trim();

            switch (fieldTrim) {
                case "item_sku":
                    if (isParent) {
                        cell.setCellValue(Optional.ofNullable(info.getSku()).orElse(""));
                    } else if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
                        cell.setCellValue(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName + "-" + sizeName);
                    } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
                        cell.setCellValue(Optional.ofNullable(info.getSku()).orElse("") + "-" + sizeName);
                    } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
                        cell.setCellValue(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName);
                    } else {
                        cell.setCellValue(Optional.ofNullable(info.getSku()).orElse(""));
                    }
                    break;
                case "item_name":
                    cell.setCellValue(getItemTitle(language, detail));
                    break;
                case "external_product_id":
                    cell.setCellValue(Optional.ofNullable(paramDTO.getUpcNode1()).orElse(""));
                    break;
                case "external_product_id_type":
                    if (hasVariant && !isParent) {
                        cell.setCellValue("Upc");
                    } else if (hasVariant && isParent) {
                        cell.setCellValue("");
                    } else {
                        cell.setCellValue("Upc");
                    }
                    break;
                // 产品分类
                case "feed_product_type":
                    cell.setCellValue(Optional.ofNullable(feed).orElse(""));
                    break;
                case "brand_name":
                    cell.setCellValue(brandName);
                    break;
                case "manufacture":
                    cell.setCellValue(manufacturer);
                    break;
                case "part_number":
                    cell.setCellValue(Optional.ofNullable(paramDTO.getUpcNode2()).orElse(""));
                    break;
                case "product_description":
                    cell.setCellValue(getItemDescription(language, detail));
                    break;
                case "update_delete":
                    cell.setCellValue("Update");
                    break;
                case "sale_price":
                    cell.setCellValue("");
                    break;
                case "currency":
                    cell.setCellValue(Optional.ofNullable(saleCurrency).orElse(""));
                    break;
                case "condition_type":
                    cell.setCellValue("New");
                    break;
                case "condition_note":
                    cell.setCellValue("");
                    break;
                case "quantity":
                    cell.setCellValue(Optional.ofNullable(stock).orElse(100));
                    break;
                case "website_shipping_weight":
                    if (weight != null) {
                        cell.setCellValue(df.format(new BigDecimal(weight).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    }
                    break;
                case "website_shipping_weight_unit_of_measure":
                    cell.setCellValue("KG");
                    break;
                // 简要描述
                case "bullet_point1":
                    cell.setCellValue((briefDescs.length > 0) ? briefDescs[0] : "");
                    break;
                case "bullet_point2":
                    cell.setCellValue((briefDescs.length > 1) ? briefDescs[1] : "");
                    break;
                case "bullet_point3":
                    cell.setCellValue((briefDescs.length > 2) ? briefDescs[2] : "");
                    break;
                case "bullet_point4":
                    cell.setCellValue((briefDescs.length > 3) ? briefDescs[3] : "");
                    break;
                case "bullet_point5":
                    cell.setCellValue((briefDescs.length > 4) ? briefDescs[4] : "");
                    break;
                // 小分类
                case "recommended_browse_nodes1":
                    cell.setCellValue(Optional.ofNullable(nodes1).orElse(""));
                    break;
                case "recommended_browse_nodes2":
                    cell.setCellValue(Optional.ofNullable(nodes2).orElse(""));
                    break;
                // 关键字
                case "generic_keywords1":
                    cell.setCellValue((genericKeywords.length > 0) ? genericKeywords[0] : "");
                    break;
                case "generic_keywords2":
                    cell.setCellValue((genericKeywords.length > 1) ? genericKeywords[1] : "");
                    break;
                case "generic_keywords3":
                    cell.setCellValue((genericKeywords.length > 2) ? genericKeywords[2] : "");
                    break;
                case "generic_keywords4":
                    cell.setCellValue((genericKeywords.length > 3) ? genericKeywords[3] : "");
                    break;
                case "generic_keywords5":
                    cell.setCellValue((genericKeywords.length > 4) ? genericKeywords[4] : "");
                    break;

                // 图片
                case "main_image_url":
                    cell.setCellValue((pictures.length >= 1) ? pictures[0] : "");
                    break;
                case "other_image_url1":
                    cell.setCellValue((pictures.length >= 2) ? pictures[1] : "");
                    break;
                case "other_image_url2":
                    cell.setCellValue((pictures.length >= 3) ? pictures[2] : "");
                    break;
                case "other_image_url3":
                    cell.setCellValue((pictures.length >= 4) ? pictures[3] : "");
                    break;
                case "other_image_url4":
                    cell.setCellValue((pictures.length >= 5) ? pictures[4] : "");
                    break;
                case "other_image_url5":
                    cell.setCellValue((pictures.length >= 6) ? pictures[5] : "");
                    break;
                case "other_image_url6":
                    cell.setCellValue((pictures.length >= 7) ? pictures[6] : "");
                    break;
                case "other_image_url7":
                    cell.setCellValue((pictures.length >= 8) ? pictures[7] : "");
                    break;
                case "other_image_url8":
                    cell.setCellValue((pictures.length >= 9) ? pictures[8] : "");
                    break;
                // 暂时未用到
                case "is_separate":
                    cell.setCellValue("");
                    break;

                // 主副关系（主产品是Parent） 副产品是：Child
                case "parent_child":
                    if (hasVariant && !isParent) {
                        cell.setCellValue("Child");
                    } else if (hasVariant && isParent) {
                        cell.setCellValue("Parent");
                    } else {
                        cell.setCellValue("");
                    }
                    break;
                // 这个地方只需要主产品的SKU，，只需要副产品填写
                case "parent_sku":
                    if (hasVariant && !isParent && info.getSku() != null) {
                        cell.setCellValue(info.getSku());
                    }
                    break;
                // 这个地方也只有副产品有这个词
                case "relationship_type":
                    if (hasVariant && !isParent) {
                        cell.setCellValue("Variation");
                    }
                    break;
                // 这里是颜色颜色和尺寸的变化主体
                case "variation_theme":
                    if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
                        cell.setCellValue("ColorSize");
                    } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
                        cell.setCellValue("Size");
                    } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
                        cell.setCellValue("Color");
                    } else {
                        cell.setCellValue("");
                    }

                    break;
                case "color_name":
                    if (!isParent) {
                        cell.setCellValue(Optional.ofNullable(colorName).orElse(""));
                    } else {
                        cell.setCellValue("");
                    }
                    break;
                case "color_map":
                    if (!isParent) {
                        cell.setCellValue(Optional.ofNullable(colorName).orElse(""));
                    } else {
                        cell.setCellValue("");
                    }
                    break;
                case "size_name":
                    if (!isParent) {
                        cell.setCellValue(Optional.ofNullable(sizeName).orElse(""));
                    } else {
                        cell.setCellValue("");
                    }
                    break;
                case "size_map":
                    if (!isParent) {
                        cell.setCellValue(Optional.ofNullable(sizeName).orElse(""));
                    } else {
                        cell.setCellValue("");
                    }
                    break;
                case "standard_price":
                    cell.setCellValue(df.format(Optional.ofNullable(price).orElse(0f)));
                    break;
                case "sale_from_date":
                    cell.setCellValue("");
                    break;
                case "sale_end_date":
                    cell.setCellValue("");
                    break;
                default:
                    break;
            }
            fieldIndex++;
        }
    }

    public List<ProductExportResultDTO> getExportProductList(List<ProductInfo> infos, List<ProductDetail> details, ProductExportParamDTO paramDTO) {
        List<ProductExportResultDTO> resultList = new ArrayList<>();

        // 查询变体库
        String colorName = "";
        String sizeName = "";
        Set<String> variantList = new HashSet<>();
        for (ProductDetail detail : details) {
            // 没有变体不处理
            if (StringUtils.isEmpty(detail.getVariantCompose())) {
                continue;
            }

            JSONArray variantCompose = JSONArray.fromObject(detail.getVariantCompose());
            String variant = detail.getVariant();
            if (StringUtils.isNotEmpty(variant)) {
                JSONArray variantArr = JSONArray.fromObject(variant);
                if (variantArr != null && !CollectionUtils.isEmpty(variantArr)) {
                    for (Object o : variantArr) {
                        JSONObject data = JSONObject.fromObject(o);
                        if (data.optString("variant", "").equals("color")) {
                            colorName = "color";
                        }
                        if (data.optString("variant", "").equals("size")) {
                            sizeName = "size";
                        }
                    }
                }
            }

            for (Object o : variantCompose) {
                JSONObject variantData = JSONObject.fromObject(o);
                String variantName = variantData.getString("name");
                if (StringUtils.isNotEmpty(variantName)) {

                    String[] variantNames = variantName.split(DELIMITER);
                    Integer length = variantNames.length;
                    if (length > 1) {
                        colorName = variantNames[0];
                        sizeName = variantNames[1];

                        variantList.add(colorName);
                        variantList.add(sizeName);
                    } else if (length > 0) {
                        if (colorName.equals("color")) {
                            colorName = variantNames[0];
                            variantList.add(colorName);
                        } else if (sizeName.equals("size")) {
                            sizeName = variantNames[0];
                            variantList.add(sizeName);
                        }
                    }
                }
            }
        }

        Map<String, String> variantMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(variantList)) {
            ProductVariantExample productVariantExample = new ProductVariantExample();
            productVariantExample.createCriteria().andOrgIdEqualTo(infos.get(0).getOrgId()).andVariantZhIn(new ArrayList<>(variantList));

            List<ProductVariant> productVariants = productVariantService.selectByExample(productVariantExample);

            if (!CollectionUtils.isEmpty(productVariants)) {
                String language = paramDTO.getLanguage();
                productVariants.forEach(p -> {
                    variantMap.put(p.getVariantZh(), getItemVariant(language, p));
                });
            }
        }

        Map<Integer, ProductDetail> productDetailMap = details.stream().collect(Collectors.toMap(ProductDetail::getProductId, p -> p, (k1, k2) -> k1));

        // 子线程异步计算的结果集
        List<Future> futureList = new ArrayList<>();
        for (ProductInfo info : infos) {
            ProductDetail detail = productDetailMap.get(info.getId());
            if (detail == null) {
                continue;
            }

            Future future = CommonThreadPool.submit(() -> {
                List<ProductExportResultDTO> itemList = new ArrayList<>();

                boolean hasVariant = StringUtils.isNotEmpty(detail.getVariantCompose()) && JSONArray.fromObject(detail.getVariantCompose()).size() > 0;

                ProductExportResultDTO exportResultDTO = getExportResultDto(paramDTO, info, detail, null, null, hasVariant, true);
                if (exportResultDTO != null) {
                    itemList.add(exportResultDTO);
                }

                if (hasVariant) {
                    JSONArray variantCompose = JSONArray.fromObject(detail.getVariantCompose());
                    for (Object o : variantCompose) {
                        JSONObject item = JSONObject.fromObject(o);

                        ProductExportResultDTO exportResultDTO1 = getExportResultDto(paramDTO, info, detail, item, variantMap, true, false);
                        if (exportResultDTO1 != null) {
                            itemList.add(exportResultDTO1);
                        }
                    }
                }

                return itemList;

            });

            futureList.add(future);
        }

        for (Future future : futureList) {
            try {
                // 阻塞等待子线陈处理完毕, Runnable的返回是null，Callable的返回是函数的返回值，此处不需要处理。
                List<ProductExportResultDTO> resultT = (List<ProductExportResultDTO>) future.get();
                resultList.addAll(resultT);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("导出失败 ", e);
            }
        }

        return resultList;
    }

    private ProductExportResultDTO getExportResultDto(ProductExportParamDTO paramDTO,
                                                      ProductInfo info, ProductDetail detail, JSONObject variantData,
                                                      Map<String, String> variantMap, boolean hasVariant, boolean isParent) {
        DecimalFormat df = new DecimalFormat("######0.00");

        String brandName = paramDTO.getBrandName();
        String manufacturer = paramDTO.getManufacturer();
        String country = paramDTO.getCountry();
        String feed = paramDTO.getFeed();
        String nodes1 = paramDTO.getNodes1();
        String nodes2 = paramDTO.getNodes2();

        String language = getLanguage(country);

        String picture = null;
        Float price = null;
        Float weight = null;
        Integer stock = null;

        String colorName = "";
        String sizeName = "";

        // 主体 为了设置主体的 variation_theme
        // [{"variant":"color","args":""},{"variant":"size","args":""}]
        if (hasVariant) {
            String variant = detail.getVariant();
            if (StringUtils.isNotEmpty(variant)) {
                JSONArray variantArr = JSONArray.fromObject(variant);
                if (variantArr != null && !CollectionUtils.isEmpty(variantArr)) {
                    for (Object o : variantArr) {
                        JSONObject data = JSONObject.fromObject(o);
                        if (data.optString("variant", "").equals("color")) {
                            colorName = "color";
                        }
                        if (data.optString("variant", "").equals("size")) {
                            sizeName = "size";
                        }
                    }
                }
            }
        }

        String titleVariantName = "";

        // 变体
        if (hasVariant && !isParent && variantData != null) {

            weight = Optional.ofNullable(variantData.optDouble("weight", Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f)).orElse(0.5d).floatValue();
            picture = variantData.optString("pic");
            Double costPrice = variantData.optDouble("price", Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f);
            if (costPrice != null) {
                price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, costPrice.floatValue(), weight);
            } else {
                price = 0f;
            }
            stock = variantData.optInt("stock", 100);

            String variantName = variantData.getString("name");
            if (StringUtils.isNotEmpty(variantName)) {

                titleVariantName = " " + variantName.replace(DELIMITER, " ");

                String[] variantNames = variantName.split(DELIMITER);
                Integer length = variantNames.length;
                if (length > 1) {
                    colorName = variantMap.getOrDefault(variantNames[0], variantNames[0]);
                    sizeName = variantMap.getOrDefault(variantNames[1], variantNames[1]);
                    titleVariantName = titleVariantName.replace(" " + variantNames[0] + " ", " " + colorName + " ");
                    titleVariantName = titleVariantName.replace(" " + variantNames[1], " " + sizeName);
                } else if (length > 0) {
                    if (colorName.equals("color")) {
                        colorName = variantMap.getOrDefault(variantNames[0], variantNames[0]);
                        titleVariantName = titleVariantName.replace(" " + variantNames[0], " " + colorName);
                    } else if (sizeName.equals("size")) {
                        sizeName = variantMap.getOrDefault(variantNames[0], variantNames[0]);
                        titleVariantName = titleVariantName.replace(" " + variantNames[0], " " + sizeName);
                    }
                }
            }
            // 主体
        } else {
            picture = detail.getPicture();
            weight = Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f;
            price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, (Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f), weight);

            stock = detail.getStock();
        }

        // 获取币种 todo
        String saleCurrency = getSaleCurrencyByCountry(country);


        // 特殊字段
        String briefDesc = getItemBriefDesc(language, detail);
        String[] briefDescs = (briefDesc == null ? "" : briefDesc).split("\\n");

        String genericKeyword = paramDTO.getKeyWord();
//                getItemKeyword(language, detail);
        String[] genericKeywords = (genericKeyword == null ? "" : genericKeyword).split("\\n");

        String[] ppictures = (picture == null ? "" : picture).split(",");
        String[] pictures = new String[ppictures.length];
        // 处理图片为1024
//        ?imageMogr2/thumbnail/1024x
        if (ppictures != null && ppictures.length > 0) {
            for (int i = 0; i < ppictures.length; i++) {
                String pic = ppictures[i];
                if (pic.contains("pic.dupf.xin")) {
                    pic = pic + "?imageMogr2/thumbnail/1024x";
                }
                pictures[i] = pic;
            }
        }

        ProductExportResultDTO resultDTO = new ProductExportResultDTO();

        //                case "item_sku":
        if (isParent) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse(""));
        } else if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName + "-" + sizeName);
        } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + sizeName);
        } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName);
        } else {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse(""));
        }
//                case "item_name":
        resultDTO.setItemName(getItemTitle(language, detail) + titleVariantName);
//                case "external_product_id":
        resultDTO.setExternalProductId(Optional.ofNullable(paramDTO.getUpcNode1()).orElse(""));
//                case "external_product_id_type":
        if (hasVariant && !isParent) {
            resultDTO.setExternalProductIdType("Upc");
        } else if (hasVariant && isParent) {
            resultDTO.setExternalProductIdType("");
        } else {
            resultDTO.setExternalProductIdType("Upc");
        }
        // 产品分类
//                case "feed_product_type":
        resultDTO.setFeedProductType(Optional.ofNullable(feed).orElse(""));
//                case "brand_name":
        resultDTO.setBrandName(brandName);
//                case "manufacture":
        resultDTO.setManufacture(manufacturer);
//                case "part_number":
        resultDTO.setPartNumber(Optional.ofNullable(paramDTO.getUpcNode2()).orElse(""));
//                case "product_description":
        resultDTO.setProductDescription(getItemDescription(language, detail));
//                case "update_delete":
        resultDTO.setUpdateDelete("Update");
//                case "sale_price":
        resultDTO.setSalePrice("");
//                case "currency":
        resultDTO.setCurrency(Optional.ofNullable(saleCurrency).orElse(""));
//                case "condition_type":
        resultDTO.setConditionType("New");
//                case "condition_note":
        resultDTO.setConditionNote("");
//                case "quantity":
        resultDTO.setQuantity(Optional.ofNullable(stock).orElse(100) + "");
//                case "website_shipping_weight":
        if (weight != null) {
            resultDTO.setWebsiteShippingWeight(df.format(new BigDecimal(weight).setScale(2, BigDecimal.ROUND_HALF_UP)));
        }
//                case "website_shipping_weight_unit_of_measure":
        resultDTO.setWebsiteShippingWeightUnitOfMeasure("KG");
//         简要描述
//                case "bullet_point1":
        resultDTO.setBulletPoint1((briefDescs.length > 0) ? briefDescs[0] : "");
//                case "bullet_point2":
        resultDTO.setBulletPoint2((briefDescs.length > 1) ? briefDescs[1] : "");
//                case "bullet_point3":
        resultDTO.setBulletPoint3((briefDescs.length > 2) ? briefDescs[2] : "");
//                case "bullet_point4":
        resultDTO.setBulletPoint4((briefDescs.length > 3) ? briefDescs[3] : "");
//                case "bullet_point5":
        resultDTO.setBulletPoint5((briefDescs.length > 4) ? briefDescs[4] : "");
        // 小分类
//                case "recommended_browse_nodes1":
        resultDTO.setRecommendedBrowseNodes1(Optional.ofNullable(nodes1).orElse(""));
//                case "recommended_browse_nodes2":
        resultDTO.setRecommendedBrowseNodes2(Optional.ofNullable(nodes2).orElse(""));
        // 关键字
//                case "generic_keywords1":
        resultDTO.setGenericKeywords1((genericKeywords.length > 0) ? genericKeywords[0] : "");
//                case "generic_keywords2":
        resultDTO.setGenericKeywords2((genericKeywords.length > 1) ? genericKeywords[1] : "");
//                case "generic_keywords3":
        resultDTO.setGenericKeywords3((genericKeywords.length > 2) ? genericKeywords[2] : "");
//                case "generic_keywords4":
        resultDTO.setGenericKeywords4((genericKeywords.length > 3) ? genericKeywords[3] : "");
//                case "generic_keywords5":
        resultDTO.setGenericKeywords5((genericKeywords.length > 4) ? genericKeywords[4] : "");

        // 图片
//                case "main_image_url":
        resultDTO.setMainImageUrl((pictures.length >= 1) ? pictures[0] : "");
//                case "other_image_url1":
        resultDTO.setOtherImageUrl1((pictures.length >= 2) ? pictures[1] : "");
//                case "other_image_url2":
        resultDTO.setOtherImageUrl2((pictures.length >= 3) ? pictures[2] : "");
//                case "other_image_url3":
        resultDTO.setOtherImageUrl3((pictures.length >= 4) ? pictures[3] : "");
//                case "other_image_url4":
        resultDTO.setOtherImageUrl4((pictures.length >= 5) ? pictures[4] : "");
//                case "other_image_url5":
        resultDTO.setOtherImageUrl5((pictures.length >= 6) ? pictures[5] : "");
//                case "other_image_url6":
        resultDTO.setOtherImageUrl6((pictures.length >= 7) ? pictures[6] : "");
//                case "other_image_url7":
        resultDTO.setOtherImageUrl7((pictures.length >= 8) ? pictures[7] : "");
//                case "other_image_url8":
        resultDTO.setOtherImageUrl8((pictures.length >= 9) ? pictures[8] : "");
        // 暂时未用到
//                case "is_separate":
        resultDTO.setIsSeparate("");

        // 主副关系（主产品是Parent） 副产品是：Child
//                case "parent_child":
        if (hasVariant && !isParent) {
            resultDTO.setParentChild("Child");
        } else if (hasVariant && isParent) {
            resultDTO.setParentChild("Parent");
        } else {
            resultDTO.setParentChild("");
        }
        // 这个地方只需要主产品的SKU，，只需要副产品填写
//                case "parent_sku":
        if (hasVariant && !isParent && info.getSku() != null) {
            resultDTO.setParentSku(info.getSku());
        }
        // 这个地方也只有副产品有这个词
//                case "relationship_type":
        if (hasVariant && !isParent) {
            resultDTO.setRelationshipType("Variation");
        }
        // 这里是颜色颜色和尺寸的变化主体
//                case "variation_theme":
        if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setVariationTheme("ColorSize");
        } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setVariationTheme("Size");
        } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
            resultDTO.setVariationTheme("Color");
        } else {
            resultDTO.setVariationTheme("");
        }

//                case "color_name":
        if (!isParent) {
            resultDTO.setColorName(Optional.ofNullable(colorName).orElse(""));
        } else {
            resultDTO.setColorName("");
        }
//                case "color_map":
        if (!isParent) {
            resultDTO.setColorMap(Optional.ofNullable(colorName).orElse(""));
        } else {
            resultDTO.setColorMap("");
        }
//                case "size_name":
        if (!isParent) {
            resultDTO.setSizeName(Optional.ofNullable(sizeName).orElse(""));
        } else {
            resultDTO.setSizeName("");
        }
//                case "size_map":
        if (!isParent) {
            resultDTO.setSizeMap(Optional.ofNullable(sizeName).orElse(""));
        } else {
            resultDTO.setSizeMap("");
        }
//                case "standard_price":
        resultDTO.setStandardPrice(df.format(Optional.ofNullable(price).orElse(0f)));
//                case "sale_from_date":
        resultDTO.setSaleFromDate("");
//                case "sale_end_date":
        resultDTO.setSaleEndDate("");

        return resultDTO;
    }

    private ProductExportResultDTO getExportResultDtoBk(ProductExportParamDTO paramDTO,
                                                        ProductInfo info, ProductDetail detail, JSONObject variantData, boolean hasVariant, boolean isParent) {
        DecimalFormat df = new DecimalFormat("######0.00");

        String brandName = paramDTO.getBrandName();
        String manufacturer = paramDTO.getManufacturer();
        String country = paramDTO.getCountry();
        String feed = paramDTO.getFeed();
        String nodes1 = paramDTO.getNodes1();
        String nodes2 = paramDTO.getNodes2();

        String language = getLanguage(country);

        String picture = null;
        Float price = null;
        Float weight = null;
        Integer stock = null;

        String colorName = "";
        String sizeName = "";

        // 主体 为了设置主体的 variation_theme
        // [{"variant":"color","args":""},{"variant":"size","args":""}]
        if (hasVariant) {
            String variant = detail.getVariant();
            if (StringUtils.isNotEmpty(variant)) {
                JSONArray variantArr = JSONArray.fromObject(variant);
                if (variantArr != null && !CollectionUtils.isEmpty(variantArr)) {
                    for (Object o : variantArr) {
                        JSONObject data = JSONObject.fromObject(o);
                        if (data.optString("variant", "").equals("color")) {
                            colorName = "color";
                        }
                        if (data.optString("variant", "").equals("size")) {
                            sizeName = "size";
                        }
                    }
                }
            }
        }

        String titleVariantName = "";

        // 变体
        if (hasVariant && !isParent && variantData != null) {

            weight = Optional.ofNullable(variantData.optDouble("weight", Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f)).orElse(0.5d).floatValue();
            picture = variantData.optString("pic");
            Double costPrice = variantData.optDouble("price", Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f);
            if (costPrice != null) {
                price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, costPrice.floatValue(), weight);
            } else {
                price = 0f;
            }
            stock = variantData.optInt("stock", 100);

            String variantName = variantData.getString("name");
            if (StringUtils.isNotEmpty(variantName)) {

                titleVariantName = " " + variantName.replace(DELIMITER, " ");

                String[] variantNames = variantName.split(DELIMITER);
                Integer length = variantNames.length;
                if (length > 1) {
                    colorName = variantNames[0];
                    sizeName = variantNames[1];
                } else if (length > 0) {
                    if (colorName.equals("color")) {
                        colorName = variantNames[0];
                    } else if (sizeName.equals("size")) {
                        sizeName = variantNames[0];
                    }
                }
            }
            // 主体
        } else {
            picture = detail.getPicture();
            weight = Optional.ofNullable(detail.getProductWeight()).orElse(500) / 1000.0f;
            price = salePriceSettingService.calculateSalePrice(info.getOrgId(), info.getCollectUserId(), country, (Optional.ofNullable(info.getCostPrice()).orElse(0) / 100.0f), weight);

            stock = detail.getStock();
        }

        // 获取币种 todo
        String saleCurrency = getSaleCurrencyByCountry(country);


        // 特殊字段
        String briefDesc = getItemBriefDesc(language, detail);
        String[] briefDescs = (briefDesc == null ? "" : briefDesc).split("\\n");

        String genericKeyword = paramDTO.getKeyWord();
//                getItemKeyword(language, detail);
        String[] genericKeywords = (genericKeyword == null ? "" : genericKeyword).split("\\n");

        String[] ppictures = (picture == null ? "" : picture).split(",");
        String[] pictures = new String[ppictures.length];
        // 处理图片为1024
//        ?imageMogr2/thumbnail/1024x
        if (ppictures != null && ppictures.length > 0) {
            for (int i = 0; i < ppictures.length; i++) {
                String pic = ppictures[i];
                if (pic.contains("pic.dupf.xin")) {
                    pic = pic + "?imageMogr2/thumbnail/1024x";
                }
                pictures[i] = pic;
            }
        }

        ProductExportResultDTO resultDTO = new ProductExportResultDTO();

        //                case "item_sku":
        if (isParent) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse(""));
        } else if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName + "-" + sizeName);
        } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + sizeName);
        } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse("") + "-" + colorName);
        } else {
            resultDTO.setItemSku(Optional.ofNullable(info.getSku()).orElse(""));
        }
//                case "item_name":
        resultDTO.setItemName(getItemTitle(language, detail) + titleVariantName);
//                case "external_product_id":
        resultDTO.setExternalProductId(Optional.ofNullable(paramDTO.getUpcNode1()).orElse(""));
//                case "external_product_id_type":
        if (hasVariant && !isParent) {
            resultDTO.setExternalProductIdType("Upc");
        } else if (hasVariant && isParent) {
            resultDTO.setExternalProductIdType("");
        } else {
            resultDTO.setExternalProductIdType("Upc");
        }
        // 产品分类
//                case "feed_product_type":
        resultDTO.setFeedProductType(Optional.ofNullable(feed).orElse(""));
//                case "brand_name":
        resultDTO.setBrandName(brandName);
//                case "manufacture":
        resultDTO.setManufacture(manufacturer);
//                case "part_number":
        resultDTO.setPartNumber(Optional.ofNullable(paramDTO.getUpcNode2()).orElse(""));
//                case "product_description":
        resultDTO.setProductDescription(getItemDescription(language, detail));
//                case "update_delete":
        resultDTO.setUpdateDelete("Update");
//                case "sale_price":
        resultDTO.setSalePrice("");
//                case "currency":
        resultDTO.setCurrency(Optional.ofNullable(saleCurrency).orElse(""));
//                case "condition_type":
        resultDTO.setConditionType("New");
//                case "condition_note":
        resultDTO.setConditionNote("");
//                case "quantity":
        resultDTO.setQuantity(Optional.ofNullable(stock).orElse(100) + "");
//                case "website_shipping_weight":
        if (weight != null) {
            resultDTO.setWebsiteShippingWeight(df.format(new BigDecimal(weight).setScale(2, BigDecimal.ROUND_HALF_UP)));
        }
//                case "website_shipping_weight_unit_of_measure":
        resultDTO.setWebsiteShippingWeightUnitOfMeasure("KG");
//         简要描述
//                case "bullet_point1":
        resultDTO.setBulletPoint1((briefDescs.length > 0) ? briefDescs[0] : "");
//                case "bullet_point2":
        resultDTO.setBulletPoint2((briefDescs.length > 1) ? briefDescs[1] : "");
//                case "bullet_point3":
        resultDTO.setBulletPoint3((briefDescs.length > 2) ? briefDescs[2] : "");
//                case "bullet_point4":
        resultDTO.setBulletPoint4((briefDescs.length > 3) ? briefDescs[3] : "");
//                case "bullet_point5":
        resultDTO.setBulletPoint5((briefDescs.length > 4) ? briefDescs[4] : "");
        // 小分类
//                case "recommended_browse_nodes1":
        resultDTO.setRecommendedBrowseNodes1(Optional.ofNullable(nodes1).orElse(""));
//                case "recommended_browse_nodes2":
        resultDTO.setRecommendedBrowseNodes2(Optional.ofNullable(nodes2).orElse(""));
        // 关键字
//                case "generic_keywords1":
        resultDTO.setGenericKeywords1((genericKeywords.length > 0) ? genericKeywords[0] : "");
//                case "generic_keywords2":
        resultDTO.setGenericKeywords2((genericKeywords.length > 1) ? genericKeywords[1] : "");
//                case "generic_keywords3":
        resultDTO.setGenericKeywords3((genericKeywords.length > 2) ? genericKeywords[2] : "");
//                case "generic_keywords4":
        resultDTO.setGenericKeywords4((genericKeywords.length > 3) ? genericKeywords[3] : "");
//                case "generic_keywords5":
        resultDTO.setGenericKeywords5((genericKeywords.length > 4) ? genericKeywords[4] : "");

        // 图片
//                case "main_image_url":
        resultDTO.setMainImageUrl((pictures.length >= 1) ? pictures[0] : "");
//                case "other_image_url1":
        resultDTO.setOtherImageUrl1((pictures.length >= 2) ? pictures[1] : "");
//                case "other_image_url2":
        resultDTO.setOtherImageUrl2((pictures.length >= 3) ? pictures[2] : "");
//                case "other_image_url3":
        resultDTO.setOtherImageUrl3((pictures.length >= 4) ? pictures[3] : "");
//                case "other_image_url4":
        resultDTO.setOtherImageUrl4((pictures.length >= 5) ? pictures[4] : "");
//                case "other_image_url5":
        resultDTO.setOtherImageUrl5((pictures.length >= 6) ? pictures[5] : "");
//                case "other_image_url6":
        resultDTO.setOtherImageUrl6((pictures.length >= 7) ? pictures[6] : "");
//                case "other_image_url7":
        resultDTO.setOtherImageUrl7((pictures.length >= 8) ? pictures[7] : "");
//                case "other_image_url8":
        resultDTO.setOtherImageUrl8((pictures.length >= 9) ? pictures[8] : "");
        // 暂时未用到
//                case "is_separate":
        resultDTO.setIsSeparate("");

        // 主副关系（主产品是Parent） 副产品是：Child
//                case "parent_child":
        if (hasVariant && !isParent) {
            resultDTO.setParentChild("Child");
        } else if (hasVariant && isParent) {
            resultDTO.setParentChild("Parent");
        } else {
            resultDTO.setParentChild("");
        }
        // 这个地方只需要主产品的SKU，，只需要副产品填写
//                case "parent_sku":
        if (hasVariant && !isParent && info.getSku() != null) {
            resultDTO.setParentSku(info.getSku());
        }
        // 这个地方也只有副产品有这个词
//                case "relationship_type":
        if (hasVariant && !isParent) {
            resultDTO.setRelationshipType("Variation");
        }
        // 这里是颜色颜色和尺寸的变化主体
//                case "variation_theme":
        if (StringUtils.isNotEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setVariationTheme("ColorSize");
        } else if (StringUtils.isEmpty(colorName) && StringUtils.isNotEmpty(sizeName)) {
            resultDTO.setVariationTheme("Size");
        } else if (StringUtils.isEmpty(sizeName) && StringUtils.isNotEmpty(colorName)) {
            resultDTO.setVariationTheme("Color");
        } else {
            resultDTO.setVariationTheme("");
        }

//                case "color_name":
        if (!isParent) {
            resultDTO.setColorName(Optional.ofNullable(colorName).orElse(""));
        } else {
            resultDTO.setColorName("");
        }
//                case "color_map":
        if (!isParent) {
            resultDTO.setColorMap(Optional.ofNullable(colorName).orElse(""));
        } else {
            resultDTO.setColorMap("");
        }
//                case "size_name":
        if (!isParent) {
            resultDTO.setSizeName(Optional.ofNullable(sizeName).orElse(""));
        } else {
            resultDTO.setSizeName("");
        }
//                case "size_map":
        if (!isParent) {
            resultDTO.setSizeMap(Optional.ofNullable(sizeName).orElse(""));
        } else {
            resultDTO.setSizeMap("");
        }
//                case "standard_price":
        resultDTO.setStandardPrice(df.format(Optional.ofNullable(price).orElse(0f)));
//                case "sale_from_date":
        resultDTO.setSaleFromDate("");
//                case "sale_end_date":
        resultDTO.setSaleEndDate("");

        return resultDTO;
    }

    /**
     * 获取指定国家对应的货币单位
     *
     * @param country
     * @return
     */
    private String getSaleCurrencyByCountry(String country) {

        String currency = "";

        for (ProductCountryConstant item : ProductCountryConstant.values()) {
            if (country.equalsIgnoreCase(item.shortName)) {
                currency = item.currency;
            }
        }
        return currency;
    }

    /**
     * 获取标题
     *
     * @param language
     * @param detail
     * @return
     */
    private String getItemTitle(String language, ProductDetail detail) {
        String title = "";

        switch (language) {
            case "zh":
                title = detail.getTitleZh() == null ? "" : detail.getTitleZh();
                break;
            case "en":
                title = detail.getTitleEn() == null ? "" : detail.getTitleEn();
                break;
            case "fr":
                title = detail.getTitleFr() == null ? "" : detail.getTitleFr();
                break;
            case "de":
                title = detail.getTitleDe() == null ? "" : detail.getTitleDe();
                break;
            case "es":
                title = detail.getTitleEs() == null ? "" : detail.getTitleEs();
                break;
            case "ja":
                title = detail.getTitleJa() == null ? "" : detail.getTitleJa();
                break;
            case "pt":
                title = detail.getTitlePt() == null ? "" : detail.getTitlePt();
                break;
            case "it":
                title = detail.getTitleIt() == null ? "" : detail.getTitleIt();
                break;
            default:
                break;
        }

        return title;
    }

    /**
     * 获取铲平描述
     *
     * @param language
     * @param detail
     * @return
     */
    private String getItemDescription(String language, ProductDetail detail) {
        String description = "";
        String lowerLang = language.toLowerCase();
        switch (lowerLang) {
            case "zh":
                description = Optional.ofNullable(detail.getDescriptionZh()).orElse("");
                break;
            case "en":
                description = Optional.ofNullable(detail.getDescriptionEn()).orElse("");
                break;
            case "fr":
                description = Optional.ofNullable(detail.getDescriptionFr()).orElse("");
                break;
            case "de":
                description = Optional.ofNullable(detail.getDescriptionDe()).orElse("");
                break;
            case "es":
                description = Optional.ofNullable(detail.getDescriptionEs()).orElse("");
                break;
            case "ja":
                description = Optional.ofNullable(detail.getDescriptionJa()).orElse("");
                break;
            case "pt":
                description = Optional.ofNullable(detail.getDescriptionPt()).orElse("");
                break;
            case "it":
                description = Optional.ofNullable(detail.getDescriptionIt()).orElse("");
                break;
            default:
                break;
        }

        try {

            if (StringUtils.isNotEmpty(description.trim())) {
                description = description.trim().replaceAll(regex1, "\n")
                        .replaceAll(regex2, "\n")
                        .replaceAll(regex3, "\n")
                        .replaceAll(regex4, "\n")
                        .replaceAll(regex11, "\n")
                        .replaceAll(regex12, "\n")
                        .replaceAll(regex13, "\n")
                        .replaceAll(regex14, "\n")
                        .replaceAll("\r\n", "\n")
                        .replaceAll("\n", "<br>\r\n");
            }
        } catch (Exception e) {
            LOGGER.error("replace <br> error", e);
        }

        return description;
    }

    /**
     * 获取关键字说明
     *
     * @param language
     * @param detail
     * @return
     */
    private String getItemKeyword(String language, ProductDetail detail) {
        String keywords = "";
        String lowerLang = language.toLowerCase();
        switch (lowerLang) {
            case "zh":
                keywords = Optional.ofNullable(detail.getKeywordZh()).orElse("");
                break;
            case "en":
                keywords = Optional.ofNullable(detail.getKeywordEn()).orElse("");
                break;
            case "fr":
                keywords = Optional.ofNullable(detail.getKeywordFr()).orElse("");
                break;
            case "de":
                keywords = Optional.ofNullable(detail.getKeywordDe()).orElse("");
                break;
            case "es":
                keywords = Optional.ofNullable(detail.getKeywordEs()).orElse("");
                break;
            case "ja":
                keywords = Optional.ofNullable(detail.getKeywordJa()).orElse("");
                break;
            case "pt":
                keywords = Optional.ofNullable(detail.getKeywordPt()).orElse("");
                break;
            case "it":
                keywords = Optional.ofNullable(detail.getKeywordIt()).orElse("");
                break;
            default:
                break;
        }

        return keywords;
    }

    /**
     * 获取简要说明
     *
     * @param language
     * @param detail
     * @return
     */
    private String getItemBriefDesc(String language, ProductDetail detail) {
        String briefDesc = "";
        String lowerLang = language.toLowerCase();
        switch (lowerLang) {
            case "zh":
                briefDesc = Optional.ofNullable(detail.getBriefDescZh()).orElse("");
                break;
            case "en":
                briefDesc = Optional.ofNullable(detail.getBriefDescEn()).orElse("");
                break;
            case "fr":
                briefDesc = Optional.ofNullable(detail.getBriefDescFr()).orElse("");
                break;
            case "de":
                briefDesc = Optional.ofNullable(detail.getBriefDescDe()).orElse("");
                break;
            case "es":
                briefDesc = Optional.ofNullable(detail.getBriefDescEs()).orElse("");
                break;
            case "ja":
                briefDesc = Optional.ofNullable(detail.getBriefDescJa()).orElse("");
                break;
            case "pt":
                briefDesc = Optional.ofNullable(detail.getBriefDescPt()).orElse("");
                break;
            case "it":
                briefDesc = Optional.ofNullable(detail.getBriefDescIt()).orElse("");
                break;
            default:
                break;
        }

        return briefDesc;
    }

    /**
     * 获取变体库对应语言
     *
     * @param language
     * @param detail
     * @return
     */
    private String getItemVariant(String language, ProductVariant detail) {
        String briefDesc = "";
        String lowerLang = language.toLowerCase();
        switch (lowerLang) {
            case "zh":
                briefDesc = Optional.ofNullable(detail.getVariantZh()).orElse("");
                break;
            case "en":
                briefDesc = Optional.ofNullable(detail.getVariantEn()).orElse("");
                break;
            case "fr":
                briefDesc = Optional.ofNullable(detail.getVariantFr()).orElse("");
                break;
            case "de":
                briefDesc = Optional.ofNullable(detail.getVariantDe()).orElse("");
                break;
            case "es":
                briefDesc = Optional.ofNullable(detail.getVariantEs()).orElse("");
                break;
            case "ja":
                briefDesc = Optional.ofNullable(detail.getVariantJa()).orElse("");
                break;
            case "pt":
                briefDesc = Optional.ofNullable(detail.getVariantPt()).orElse("");
                break;
            case "it":
                briefDesc = Optional.ofNullable(detail.getVariantIt()).orElse("");
                break;
            default:
                break;
        }

        return StringUtils.isNotEmpty(briefDesc) ? briefDesc : Optional.ofNullable(detail.getVariantZh()).orElse("");
    }

    private String getLanguage(String country) {
        String language = "";

        for (ProductCountryConstant item : ProductCountryConstant.values()) {
            if (country.equalsIgnoreCase(item.shortName)) {
                language = item.language;
            }
        }
        return language;
    }

    private ProductDetail copyProductDetail(ProductDetail sourceProductDetail) {
        ProductDetail targetProductDetail = new ProductDetail();
        targetProductDetail.setProductId(sourceProductDetail.getProductId());
        targetProductDetail.setStock(sourceProductDetail.getStock());
        targetProductDetail.setProductWeight(sourceProductDetail.getProductWeight());
        targetProductDetail.setPackageWeight(sourceProductDetail.getPackageWeight());
        targetProductDetail.setFreeShipping(sourceProductDetail.getFreeShipping());
        targetProductDetail.setDelivery24(sourceProductDetail.getDelivery24());
        targetProductDetail.setFba(sourceProductDetail.getFba());
        targetProductDetail.setBrandName(sourceProductDetail.getBrandName());
        targetProductDetail.setManufacturer(sourceProductDetail.getManufacturer());
        targetProductDetail.setProduceNo(sourceProductDetail.getProduceNo());
        targetProductDetail.setMark(sourceProductDetail.getMark());
        targetProductDetail.setPicture(sourceProductDetail.getPicture());
        targetProductDetail.setTitleZh(sourceProductDetail.getTitleZh());
        targetProductDetail.setTitleEn(sourceProductDetail.getTitleEn());
        targetProductDetail.setTitleFr(sourceProductDetail.getTitleFr());
        targetProductDetail.setTitleDe(sourceProductDetail.getTitleDe());
        targetProductDetail.setTitleEs(sourceProductDetail.getTitleEs());
        targetProductDetail.setTitleJa(sourceProductDetail.getTitleJa());
        targetProductDetail.setTitlePt(sourceProductDetail.getTitlePt());
        targetProductDetail.setKeywordZh(sourceProductDetail.getKeywordZh());
        targetProductDetail.setKeywordEn(sourceProductDetail.getKeywordEn());
        targetProductDetail.setKeywordFr(sourceProductDetail.getKeywordFr());
        targetProductDetail.setKeywordDe(sourceProductDetail.getKeywordDe());
        targetProductDetail.setKeywordEs(sourceProductDetail.getKeywordEs());
        targetProductDetail.setKeywordJa(sourceProductDetail.getKeywordJa());
        targetProductDetail.setKeywordPt(sourceProductDetail.getKeywordPt());
        targetProductDetail.setCtime(sourceProductDetail.getCtime());
        targetProductDetail.setVariant(sourceProductDetail.getVariant());
        targetProductDetail.setVariantCompose(sourceProductDetail.getVariantCompose());
        targetProductDetail.setDescriptionZh(sourceProductDetail.getDescriptionZh());
        targetProductDetail.setDescriptionEn(sourceProductDetail.getDescriptionEn());
        targetProductDetail.setDescriptionFr(sourceProductDetail.getDescriptionFr());
        targetProductDetail.setDescriptionDe(sourceProductDetail.getDescriptionDe());
        targetProductDetail.setDescriptionEs(sourceProductDetail.getDescriptionEs());
        targetProductDetail.setDescriptionJa(sourceProductDetail.getDescriptionJa());
        targetProductDetail.setDescriptionPt(sourceProductDetail.getDescriptionPt());
        targetProductDetail.setBriefDescZh(sourceProductDetail.getBriefDescZh());
        targetProductDetail.setBriefDescEn(sourceProductDetail.getBriefDescEn());
        targetProductDetail.setBriefDescFr(sourceProductDetail.getBriefDescFr());
        targetProductDetail.setBriefDescDe(sourceProductDetail.getBriefDescDe());
        targetProductDetail.setBriefDescEs(sourceProductDetail.getBriefDescEs());
        targetProductDetail.setBriefDescJa(sourceProductDetail.getBriefDescJa());
        targetProductDetail.setBriefDescPt(sourceProductDetail.getBriefDescPt());

        return targetProductDetail;
    }

    private ProductInfo copyProductInfo(ProductInfo sourceProductInfo) {
        ProductInfo targetProductInfo = new ProductInfo();
        targetProductInfo.setOrgId(sourceProductInfo.getOrgId());
        targetProductInfo.setMainPic(sourceProductInfo.getMainPic());
        targetProductInfo.setTitle(sourceProductInfo.getTitle());
        targetProductInfo.setCategory(sourceProductInfo.getCategory());
        targetProductInfo.setCategoryId(sourceProductInfo.getCategoryId());
        targetProductInfo.setProductNo(sourceProductInfo.getProductNo());
        targetProductInfo.setSku(sourceProductInfo.getSku());
        targetProductInfo.setCostPrice(sourceProductInfo.getCostPrice());
        targetProductInfo.setCostCurUnit(sourceProductInfo.getCostCurUnit());
        targetProductInfo.setSalePrice(sourceProductInfo.getSalePrice());
        targetProductInfo.setSaleCurUnit(sourceProductInfo.getSaleCurUnit());
        targetProductInfo.setSourceDomain(sourceProductInfo.getSourceDomain());
        targetProductInfo.setSourceUrl(sourceProductInfo.getSourceUrl());
        targetProductInfo.setProductTag(sourceProductInfo.getProductTag());
        targetProductInfo.setStatus(sourceProductInfo.getStatus());
        targetProductInfo.setReleaseTime(sourceProductInfo.getReleaseTime());
        targetProductInfo.setCollectUserId(sourceProductInfo.getCollectUserId());
        targetProductInfo.setCtime(sourceProductInfo.getCtime());
        targetProductInfo.setOrders(sourceProductInfo.getOrders());

        return targetProductInfo;
    }

    public static void main(String[] args) {

        String aa = "<b>Compact Design The shoe rack’s compact size makes it a perfect fit for any space in the home. It can fit in any corner or nook of your house. Moreover, it is lightweight, which enables easier portability throughout the house.</b><br/><br/>\n" +
                "<b>Installation instructions details: Provide installation instructions. Provide simple installation tools</b><br/><br/>\n" +
                "MULTIFUNCTIONAL BAMBOO RACK: Natural bamboo frame, MDF boards, environment friendly and sturd. rack & storage shelf for shoes, bags, plants, toiletries, baskets, books, DVD-CD in entryway, bedroom, bathroom, balcony, closet, etc.<br><br>\n" +
                "\n" +
                "Simple stylish design yet functional and suitable for any room<br><br>\n" +
                "Compact Design The shoe rack’s compact size makes it a perfect fit for any space in the home. It can fit in any corner or nook of your house. Moreover, it is lightweight, which enables easier portability throughout the house.<br><br>\n" +
                "Designed with removable built-in fittings, all fittings have been treated for rust prevention, the anti-rust and durable screws make the rack more stable and easy to assemble and disassembled.<br>\n" +
                "\n" +
                "Style positioning: economical<br/>\n" +
                "Additional features: disassembly and assembly<br/>\n" +
                "Furniture structure: bracket structure<br/>\n" +
                "Material: Bamboo<br/>\n" +
                "\n" +
                "\n";


        String regex1 = "<br>\\s+\\r\\n";
        String regex2 = "<Br>\\s+\\r\\n";
        String regex3 = "<bR>\\s+\\r\\n";
        String regex4 = "<BR>\\s+\\r\\n";
        String regex11 = "<br>\\s?\\n";
        String regex12 = "<Br>\\s?\\n";
        String regex13 = "<bR>\\s?\\n";
        String regex14 = "<BR>\\s?\\n";

        System.out.println(aa.replaceAll(regex1, "\n")
                .replaceAll(regex2, "\n")
                .replaceAll(regex3, "\n")
                .replaceAll(regex4, "\n")
                .replaceAll(regex11, "\n")
                .replaceAll(regex12, "\n")
                .replaceAll(regex13, "\n")
                .replaceAll(regex14, "\n")
                .replaceAll("\r\n", "\n")
                .replaceAll("\n", "<br>\r\n")
        );

    }

}